package com.qcrud.mapper;

import com.qcrud.Qcrud;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

public record MapperProxy<T>(Qcrud qcrud, Map<Method, MapperMethod> methodCache)
        implements InvocationHandler, Serializable {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        return cachedMapperMethod(method).execute(args);
    }

    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(qcrud, method);
            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }
}
